package com.senyint.imsdk.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * String工具类
 * 
 * @author chenggang
 * 
 */
public class StringUtil {

    static final String TAG = "StringUtil";
    public static String PASSWORD = "^[0-9a-zA-Z@#%*&$';<>+-.,_]{6,24}$";

    public static String TELFORMAT = "^[0-9-]{7,20}$";

    /**
     * 验证是否是正确的邮箱格式
     * 
     * @param email
     * @return true表示是正确的邮箱格式,false表示不是正确邮箱格式
     */
    public static boolean isEmail(String email) {
        // 1、\\w+表示@之前至少要输入一个匹配字母或数字或下划线、点、中横线
        String regular = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
        Pattern pattern = Pattern.compile(regular);
        boolean flag = false;
        if (email != null) {
            Matcher matcher = pattern.matcher(email);
            flag = matcher.matches();
        }
        return flag;
    }

    /**
     * 座机电话校验
     * 
     * @param tel
     * @return
     */
    public static boolean isRightTel(String tel) {
        Pattern pattern = Pattern.compile(TELFORMAT);
        Matcher matcher = pattern.matcher(tel);
        if (matcher.matches()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 证件编号校验
     * 
     * @param tel
     * @return
     */
    public static boolean isPcNO(String pcno) {
        String format = "^[0-9]{5,50}$";
        Pattern pattern = Pattern.compile(format);
        Matcher matcher = pattern.matcher(pcno);
        if (matcher.matches()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 是否为手机号
     * 
     * @param phone
     * @return
     */
    public static boolean isPhone(String phone) {
        Pattern pattern = Pattern.compile("0?(13|14|15|18|17)[0-9]{9}$");
        Matcher matcher = pattern.matcher(phone);
        if (matcher.matches()) {
            return true;
        } else {
            return false;
        }
    }

    public static String getFloat(String f, String format) {
        if (isEmpty(f)) {
            return "";
        }
        float fl = Float.valueOf(f.trim());
        java.text.DecimalFormat df2 = new DecimalFormat(format);
        return df2.format(fl);
    }

    /**
     * 验证密码是否合适
     * 
     * @param password
     * @return
     */
    public static boolean checkPassword(String password) {
        Pattern pattern = Pattern.compile(PASSWORD);
        Matcher matcher = pattern.matcher(password);
        if (matcher.matches()) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean isEmpty(Object s) {
    	return s == null || s.toString().trim().length() == 0 || "null".equals(s) ;
    }

    
    public static int getChineseLength(String value) {
        int valueLength = 0;
        String chinese = "[\u0391-\uFFE5]";
        for (int i = 0; i < value.length(); i++) {
            String temp = value.substring(i, i + 1);
            if (temp.matches(chinese)) {
                valueLength += 1;
            }
        }
        return valueLength;
    }

    /**
     * 判断字符是否被包括在字符数组里
     * 
     * @param str
     * @param arry
     * @param ch
     * @return
     */
    public static boolean contiansInArray(String str, String arry, String ch) {
        if (arry != null && arry.length() > 0) {
            String[] idArry = arry.split(ch);
            if (idArry != null && idArry.length > 0) {
                for (int i = 0; i < idArry.length; i++) {
                    if (idArry[i].trim().equals(str.trim())) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * 先用,分隔，再用_分隔，判断字符是否被包括在分隔后的第一个字符里
     * 
     * @param str
     * @param arry
     * @param ch
     * @return
     */
    public static boolean contiansInArray(String str, String arry) {
        if (arry != null && arry.length() > 0) {
            String[] idArry = arry.split(",");
            if (idArry != null && idArry.length > 0) {
                for (int i = 0; i < idArry.length; i++) {
                    String inquiry = idArry[i].split("_")[0];
                    if (inquiry.trim().equals(str.trim())) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    public static HashMap<String, String> getMapInArray(String arry, String ch) {
        HashMap<String, String> map = new HashMap<String, String>();
        if (arry != null && arry.length() > 0) {
            String[] idArry = arry.split(ch);
            if (idArry != null && idArry.length > 0) {
                for (int i = 0; i < idArry.length; i++) {
                    map.put(idArry[i], idArry[i]);
                }
            }
        }
        return map;
    }

    /**
     * 删除字符数组中的字符,并去掉最后一位分隔符
     * 
     * @param str
     * @param arry
     * @param ch
     * @return
     */
    public static String deleteStringInArray(String str, String arry, String ch) {
        StringBuffer sbBuffer = new StringBuffer();
        if (arry != null && arry.length() > 0) {
            String[] idArry = arry.split(ch);
            if (idArry != null && idArry.length > 0) {
                for (int i = 0; i < idArry.length; i++) {
                    if (!idArry[i].trim().equals(str.trim())) {
                        sbBuffer.append(idArry[i] + ",");
                    }
                }
            }
        }
        if (sbBuffer.length() > 0) {
            String endChar = String.valueOf(sbBuffer.charAt(sbBuffer.length() - 1));
            if (endChar != null && endChar.equals(ch)) {
                sbBuffer.deleteCharAt(sbBuffer.length() - 1);
            }
        }
        if (sbBuffer.length() > 0) {
            String beginChar = String.valueOf(sbBuffer.charAt(0));
            if (beginChar != null && beginChar.equals(ch)) {
                sbBuffer.deleteCharAt(0);
            }
        }
        return sbBuffer.toString();
    }

    /**
     * 将字符串转成MD5值
     * 
     * @param string
     * @return
     */
    public static String stringToMD5(String string) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10)
                hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString();
    }

    /**
     * , 分割标签 tags
     * 
     * @param str
     * @return
     */
    public static String[] splitStrings(String str) {
        String[] strs = str.split(",");
        return strs;
    }

    public static boolean isDraw(int price) {// 提现金额
        boolean flag = false;
        if (price >= 50 && price <= 50000) {
            flag = true;
        }
        return flag;
    }

    public static boolean isRecharge(int price) {// 充值金额
        boolean flag = false;
        if (price > 0 && price <= 99999) {
            flag = true;
        }
        return flag;
    }

    public static boolean isServicePrice(int price) {// 服务价格
        boolean flag = false;
        if (price <= 9999) {
            flag = true;
        }
        return flag;
    }

    public static boolean isServiceLimit(int limit) {// 服务周期
        boolean flag = false;
        if (limit >= 2 && limit <= 999) {
            flag = true;
        }
        return flag;
    }

    public static boolean isVideoPrice(int video) {// 视频定价
        boolean flag = false;
        if (video >= 1 && video <= 9999) {
            flag = true;
        }
        return flag;
    }

    /**
     * 验证是否是 2-12个字的姓名格式
     * 
     * @param realName
     * @return
     */
    public static boolean isRealName(String realName) {
        String regular = "^[.a-zA-Z\u4E00-\u9FA5]{2,12}$";
        Pattern pattern = Pattern.compile(regular);
        boolean flag = false;
        if (!StringUtil.isEmpty(realName)) {
            Matcher matcher = pattern.matcher(realName.trim());
            flag = matcher.matches();
        }
        return flag;
    }

    /**
     * 判断身高
     * 
     * @param heightStr
     * @return
     */
    public static boolean isHeight(String heightStr) {
        try {
            int height = Integer.parseInt(heightStr);
            if (height >= 1 && height <= 300) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return false;
    }

    /**
     * 判断体重
     * 
     * @param heightStr
     * @return
     */
    public static boolean isWeight(String weightStr) {
        // String regular = "^[123]\\d{0,2}(\\.\\d*)?$";
        // Pattern pattern = Pattern.compile(regular);
        // boolean flag = false;
        // if (!StringUtil.isEmpty(weightStr)) {
        // Matcher matcher = pattern.matcher(weightStr);
        // flag = matcher.matches();
        // }
        // if (!flag) {
        // return false;
        // }
        try {
            float weight = Float.parseFloat(weightStr);
            if (weight >= 1 && weight <= 300) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return false;
    }

    /**
     * 验证是否是emoji表情 true是不包含，false是包含
     * 
     * @param content
     * @return
     */
    public static boolean containEmoji(String nickName) {
        if (isEmpty(nickName)) {
            return true;
        }
        nickName = nickName.replace("\n", "").replace("\r", "");
        String regular = "^[0-9a-zA-Z\u0024-\uFFFF #!]+$";
        Pattern pattern = Pattern.compile(regular);
        boolean flag = false;
        if (!StringUtil.isEmpty(nickName)) {
            Matcher matcher = pattern.matcher(nickName.trim());
            flag = matcher.matches();
        }
        return flag;
    }

    /**
     * 验证是否是 1-8个字的昵称格式
     * 
     * @param nickName
     * @return
     */
    public static boolean checkNickName(String nickName) {
        String regular = "^[0-9a-zA-Z\u4E00-\u9FA5 ]{1,8}$";
        Pattern pattern = Pattern.compile(regular);
        boolean flag = false;
        if (!StringUtil.isEmpty(nickName)) {
            Matcher matcher = pattern.matcher(nickName);
            flag = matcher.matches();
        }
        return flag;
    }

    /**
     * 验证是否是 1-12个字的卡片名格式
     * 
     * @param nickName
     * @return
     */
    public static boolean isCardName(String nickName) {
        String regular = "^[0-9a-zA-Z\u4E00-\u9FA5]{1,12}$";
        Pattern pattern = Pattern.compile(regular);
        boolean flag = false;
        if (!StringUtil.isEmpty(nickName)) {
            Matcher matcher = pattern.matcher(nickName);
            flag = matcher.matches();
        }
        return flag;
    }

    static int[] codeArray = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
    static Map<Integer, String> checkCodeDic = new HashMap<Integer, String>();
    static {
        checkCodeDic.put(0, "1");
        checkCodeDic.put(1, "0");
        checkCodeDic.put(2, "X");
        checkCodeDic.put(3, "9");
        checkCodeDic.put(4, "8");
        checkCodeDic.put(5, "7");
        checkCodeDic.put(6, "6");
        checkCodeDic.put(7, "5");
        checkCodeDic.put(8, "4");
        checkCodeDic.put(9, "3");
        checkCodeDic.put(10, "2");
    }

    /**
     * 验证是否是身份证号
     * 
     * @param idCard
     * @return
     */
    public static boolean isIdCard(String idCard) {
        if (isEmpty(idCard) || idCard.length() != 18) {
            return false;
        }
        int sumValue = 0;
        for (int i = 0; i < 17; i++) {
            char ch = idCard.charAt(i);
            if (!Character.isDigit(ch)) {
                return false;
            }
            sumValue += Integer.valueOf("" + ch) * codeArray[i];
        }
        int checkKey = sumValue % 11;
        String checkCode = checkCodeDic.get(checkKey);
        if (idCard.substring(idCard.length() - 1).toUpperCase().equals(checkCode)) {
            return true;
        }
        return false;
    }

    /**
     * 验证是否是 6-11个数字的邀请码格式
     * 
     * @param inviteCode
     * @return
     */
    public static boolean isInviteCode(String inviteCode) {
        String regular = "^[0-9]{6,11}$";
        Pattern pattern = Pattern.compile(regular);
        boolean flag = false;
        if (!StringUtil.isEmpty(inviteCode)) {
            Matcher matcher = pattern.matcher(inviteCode);
            flag = matcher.matches();
        }
        return flag;
    }

    /**
     * 字符类型识别函数
     * 
     * @param ch
     *            如果不是汉字、字母、数字则返回false
     */
    public static boolean charDistinguish(char ch) {
        if (Character.getType(ch) == Character.OTHER_LETTER) {// 汉字
            System.out.println("chinese_leter:" + ch);
            return true;
        } else if (Character.isDigit(ch)) {// 数字
            System.out.println("digit:" + ch);
            return true;
        } else if (Character.isLetter(ch)) {// 字母
            System.out.println("letter:" + ch);
            return true;
        } else {// 其它字符
            System.out.println("others:" + ch);
            return false;
        }
    }
    
    /**
     * 把元转成分
     */
    public static String getStringForMonery(float monery){
        DecimalFormat decimalFormat=new DecimalFormat(".00");
        return decimalFormat.format(monery);
    }

    /**
     * 判断是中文
     * 
     * @param c
     * @return
     */
    public static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return true;
        }
        return false;
    }

    /**
     * 判断输入值是否为空值，如null或者空格
     * 
     * @param obj
     *            要判断的对象
     * @return true/false,如为空则返回true
     */
    public static boolean isBlank(Object obj) {
        return obj == null || obj.toString().trim().length() == 0;
    }

    /**
     * 
     * @param inStr
     * @return
     */
    public static String getMD5(String inStr) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }
        char[] charArray = inStr.toCharArray();
        byte[] byteArray = new byte[charArray.length];
        for (int i = 0; i < charArray.length; i++)
            byteArray[i] = (byte) charArray[i];
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16)
                hexValue.append("0");
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }

    public static String getStringRemoveHtml(String text) {
        return text.replace("<br/>", "").replace("<br />", "").replace("<p>", "").replace("</p>", "");
    }

    public static String getString(int id) {
        int tmp = id > -1 ? id : 0;
        return "" + tmp;
    }
    
    
    /**
    *
    * @param dataStr
    * @return String
    */
   public static String Unicode2GBK(String dataStr) {
       int index = 0;
       StringBuffer buffer = new StringBuffer();

       int li_len = dataStr.length();
       while (index < li_len) {
           if (index >= li_len - 1
                   || !"\\u".equals(dataStr.substring(index, index + 2))) {
               buffer.append(dataStr.charAt(index));

               index++;
               continue;
           }

           String charStr = "";
           charStr = dataStr.substring(index + 2, index + 6);

           char letter = (char) Integer.parseInt(charStr, 16);

           buffer.append(letter);
           index += 6;
       }

       return buffer.toString();
   }

   /**
    * 16jinzhi>string
    * @param hex
    * @return
    */
   public static byte[] hexStringToByte(String hex) {   
	    int len = (hex.length() / 2);   
	    byte[] result = new byte[len];   
	    char[] achar = hex.toCharArray();   
	    for (int i = 0; i < len; i++) {   
	     int pos = i * 2;   
	     result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));   
	    }   
	    return result;   
	}  
	  
	private static byte toByte(char c) {   
	    byte b = (byte) "0123456789ABCDEF".indexOf(c);   
	    return b;   
	}  
	  
	/**  
	    * 把字节数组转换成16进制字符串  
	    * @param bArray  
	    * @return  
	    */   
	public static final String bytesToHexString(byte[] bArray) {   
	    StringBuffer sb = new StringBuffer(bArray.length);   
	    String sTemp;   
	    for (int i = 0; i < bArray.length; i++) {   
	     sTemp = Integer.toHexString(0xFF & bArray[i]);   
	     if (sTemp.length() < 2)   
	    	 sb.append(0);   
	     	sb.append(sTemp.toUpperCase());   
	    }   
	    return sb.toString();   
	}  
	
	/**
	 * 参数编码
	 * 
	 * @param
	 * @return
	 */
	public static String encode(String url) {
		if (url == null) {
			return "";
		}
		try {
			return URLEncoder.encode(url, "UTF-8").replace("+", "%20")
					.replace("*", "%2A").replace("%7E", "~")
					.replace("#", "%23");
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	/**
	 * 参数反编码
	 * 
	 * @param url
	 * @return
	 */
	public static String decode(String url) {
		if (url == null) {
			return "";
		}
		try {
			return URLDecoder.decode(url, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}
	
	
}
